package com.drinkdelivery.front.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.drinkdelivery.common.result.CommonResult;
import com.drinkdelivery.common.result.CommonResultCode;
import com.drinkdelivery.common.token.TokenComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author lzhCreate
 * @create 2024-07-20 11:25
 */
@Component
public class TokenValidationFilter extends OncePerRequestFilter {

    @Autowired
    private TokenComponent tokenComponent;

    private static final List<String> EXCLUDED_PATHS =
            Arrays.asList(
                    "/api/front/auth/**",
                    "/front/**",
                    "**/doc.html",
                    "/webjars/**",
                    "/swagger**",
                    "/v2/api-docs"
            );


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
//        response.setCharacterEncoding("UTF-8");

        //排除路径
        String requestURI = request.getRequestURI();
        if (isExcludedPath(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = tokenComponent.getToken(request);

        if (StrUtil.isBlank(token)) {
            response.getWriter().write(JSONObject.toJSONString(CommonResult.failed(CommonResultCode.UNAUTHORIZED)));
            return;
        }

        Boolean result = tokenComponent.check(token);
        if (!result) {
            response.getWriter().write(JSONObject.toJSONString(CommonResult.failed(CommonResultCode.PERMISSION_EXPIRATION)));
            return;
        }

        // 如果token有效，则继续处理请求
        filterChain.doFilter(request, response);
    }

    /**
     * 检查请求 URI 是否匹配任何排除路径。
     *
     * @param requestURI 请求 URI
     * @return 如果请求 URI 被排除，则返回 true，否则返回 false
     */
    private boolean isExcludedPath(String requestURI) {
        return EXCLUDED_PATHS.stream().anyMatch(excludedPath -> pathMatches(excludedPath, requestURI));
    }

    /**
     * 使用通配符匹配检查给定路径是否与请求 URI 匹配。
     *
     * @param pattern 用于匹配的模式（支持 '*' 作为通配符）
     * @param uri 请求 URI
     * @return 如果模式匹配 URI，则返回 true，否则返回 false
     */
    private boolean pathMatches(String pattern, String uri) {
        String regex = pattern.replace("*", ".*");
        return uri.matches(regex);
    }
}